package com.xuexiang.keycodelistener;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;

import java.io.File;

public class MainActivity extends AppCompatActivity implements KeyEventManager.KeyEventSubscriber {

    TextView tv1;
    TextView tv2;

    boolean isStart;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv1 = findViewById(R.id.tv_message1);
        tv2 = findViewById(R.id.tv_message2);

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.e("xuexiang", "系统的keyCode:" + keyCode);
        tv1.setText(String.format("系统的keyCode:%d", keyCode));
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                return false;
            case KeyEvent.KEYCODE_HOME:
                return false;
            default:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onKeyDown(final int keyCode) {
        tv2.setText(String.format("keyCode:%d", keyCode));
        Log.e("xuexiang", "keyCode:" + keyCode);
    }

    public void onClick(View view) {
        switch(view.getId()) {
            case R.id.button1:
                if (isStart) {
                    return;
                }
                KeyEventManager.getInstance().registerKeyEventSubscriber(this);
                isStart = true;
                break;
            case R.id.button2:
                if (!isStart) {
                    return;
                }
                KeyEventManager.getInstance().unregisterKeyEventSubscriber(this);
                isStart = false;
                break;
            default:
                break;
        }
    }
}
